// from mcqueenorama at gmail dot com; see also
// http://groups-beta.google.com/group/Google-Maps-API/browse_thread/thread/fdb49a801fd6bf7d/afafb60f21f3d556

var g_map;
var infowindow = null;
var map;

function zoomIncrement(boundsSize, dataSize, exp) {
	var new_exp;
	if ((dataSize.width > boundsSize.width * Math.pow(2, exp))
			|| (dataSize.height > boundsSize.height * Math.pow(2, exp))) {
		if (exp < 0)
			return exp + 1;
		new_exp = exp + 1;
	} else {
		if (exp > 0)
			return exp;
		new_exp = exp - 1;
	}

	return zoomIncrement(boundsSize, dataSize, new_exp);
}

function makerUrl(x) {
	var imageurl = x.getElementsByTagName("icon")[0].getAttribute("image");
	// alert(imageurl);
	// for safari, where & => &#38; and .replace doesn't seem to work
	while (imageurl.indexOf('&#38;') != -1) {
		var pos = imageurl.indexOf('&#38;');
		imageurl = imageurl.substring(0, pos) + "&"
				+ imageurl.substring(pos + "&#38;".length);
	}
	return imageurl;
}

function _makeMarker(map, x) {
	// location
	// var point = new
	// GLatLng(x.getElementsByTagName("point")[0].getAttribute("lat"),
	// x.getElementsByTagName("point")[0].getAttribute("lng"));
	var point = new google.maps.LatLng(x.getElementsByTagName("point")[0]
			.getAttribute("lat"), x.getElementsByTagName("point")[0]
			.getAttribute("lng"));
	// icon
	// var icon = new GIcon();
	var imageurl = x.getElementsByTagName("icon")[0].getAttribute("image");
	// alert(imageurl);
	// for safari, where & => &#38; and .replace doesn't seem to work
	while (imageurl.indexOf('&#38;') != -1) {
		var pos = imageurl.indexOf('&#38;');
		imageurl = imageurl.substring(0, pos) + "&"
				+ imageurl.substring(pos + "&#38;".length);
	}

	/*
	 * icon.image = imageurl; icon.shadow =
	 * "http://www.google.com/mapfiles/shadow50.png"; icon.iconSize = new
	 * GSize(40, 34); icon.shadowSize = new GSize(67, 34); icon.iconAnchor = new
	 * GPoint(19, 34); icon.infoWindowAnchor = new GPoint(19, 0);
	 * icon.infoShadowAnchor = new GPoint(38, 25);
	 */
	// marker
	// var marker = new GMarker(point,icon);
	var info = x.getElementsByTagName("div")[0];
	/*
	 * GEvent.addListener(marker, "click", function() {
	 * marker.openInfoWindow(info); map.panTo(point); });
	 * 
	 */
	var marker = new google.maps.Marker({
		position : point,
		map : map,
		icon : imageurl
	});

	var infowindow = new google.maps.InfoWindow({
		content : info
	});

	google.maps.event.addListener(marker, 'click', function() {
		infowindow.open(map, marker);
	});

	return marker;
}

// displays xml generated by longwell
function _Gdisplay(x) {
	// console.debug(x);
	document.getElementById('loading').style.display = 'none';
	var mapinfo = x.documentElement.getElementsByTagName("center");
	var center = new google.maps.LatLng(mapinfo[0].getAttribute("lat"),
			mapinfo[0].getAttribute("lng"));
	if (mapinfo[0].getAttribute("lat") == "NaN"
			|| mapinfo[0].getAttribute("lng") == "NaN") {
		center = new google.maps.LatLng(46.06, 11.11);
	}

	var myOptions = {
		zoom : 8,
		center : center,
		mapTypeId : google.maps.MapTypeId.ROADMAP
	}

	map = new google.maps.Map(document.getElementById("map"), myOptions);// new
																			// GMap2(document.getElementById("map"));

	var markers = x.documentElement.getElementsByTagName("location");
	var point = new google.maps.LatLng(x.getElementsByTagName("point")[0]
			.getAttribute("lat"), x.getElementsByTagName("point")[0]
			.getAttribute("lng"));
	for ( var i = 0; i < markers.length; i++) {
		_makeMarker(map, markers[i]);
		// map.addOverlay(marker);
	}

	var polygons = x.documentElement.getElementsByTagName("polygon");
	
	
	

	for (var j = 0; j < polygons.length; j++) {
		infowindow = new google.maps.InfoWindow();
		var points = polygons[j].getElementsByTagName("point");
		var coordinates = [];
		var latLongForZoom;
		for ( var k = 1; k < points.length; k++) {
			var latitudine = points[k].getAttribute("latitudine");
			var longitudine = points[k].getAttribute("longitudine");
			coordinates.push(new google.maps.LatLng(latitudine, longitudine));
			if (k == points.length) {
				latLongForZoom = new google.maps.LatLng(latitudine, longitudine);
			}
		}
		var infos = polygons[j].getElementsByTagName("info");
		var numParticella = infos[0].getAttribute("numParticella");
		
	      var polygonMarker = new google.maps.Marker({
	          map: map,
	          position: new google.maps.LatLng(points[0].getAttribute("latitudine"), points[0].getAttribute("longitudine")),
	          visible: false
	        });
		
	      //var boxText = document.createElement("div");
	      //boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
	      var boxText = "<div>"+numParticella+"</div>";
	      
	      var myOptions = {       
	    	        content: boxText,
	    	        maxWidth: 0,
	    	        pixelOffset: new google.maps.Size(-140, 0),
	    	        zIndex: null,
	    	        boxStyle: {  opacity: 0.75, width: "50px" } ,
	    	        closeBoxMargin: "10px 2px 2px 2px",
	    	        closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
	    	        infoBoxClearance: new google.maps.Size(1, 1),
	    	        isHidden: false,
	    	        pane: "floatPane",
	    	        enableEventPropagation: false
	      }
	      
		
		// console.debug(coordinates.length);
		var polygonToDraw = new google.maps.Polygon({
			paths : coordinates,
			strokeColor : "#FF0000",
			strokeOpacity : 0.8,
			strokeWeight : 2,
			fillColor : "#FF0000",
			fillOpacity : 0.35
		});

		polygonToDraw.setMap(map);

	      // listener responds to a click inside polygon
	      google.maps.event.addListener(polygonToDraw, "click", function (e) {
	        ib.open(map, polygonMarker);
	      });

	      var ib = new InfoBox(myOptions);
	}

	// legend - if it doesn't work, don't worry, just assume it isn't there
	try {
		var legend = x.documentElement.getElementsByTagName("legend")[0];
		window.parent.Map_setLegend(legend);
	} catch (e) {
	}
	// }
}

// run after page is loaded
function _initGMap() {

	var urlOffset = document.location.search.indexOf("url=") + "url=".length;
	var url = document.location.search.substring(urlOffset);
	url = unescape(url);

	try {
		var xmlhttp = new XMLHttpRequest();// GXmlHttp.create();
		xmlhttp.open("GET", url, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				_Gdisplay(xmlhttp.responseXML);
			}
		}
		xmlhttp.send(null); // Whoops, IE *needs* this to be last, Moz is
							// lenient.
	} catch (e) {
		// um...this try/catch seems to enable Safari functionality...
	}
}

function GMapToFacetRestriction() {
	var bounds = g_map.getBounds();
	var sw = bounds.getSouthWest();
	var ne = bounds.getNorthEast();
	// lng1,lat1,lng2,lat2
	var val = sw.x + "~" + sw.y + "|" + ne.x + "~" + ne.y;
	val = val.replace(/ /g, "");
	var mapFacetURL = parent.document.getElementById("restrictor")
			.getAttribute("mapRestrictorURL")
			+ escape(val) + "&";

	parent.window.location = mapFacetURL;
}
